package com.www.applyword.ui.my;

import android.app.Dialog;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.classic.adapter.CommonRecyclerAdapter;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.www.applyword.Constants.Constants;
import com.www.applyword.R;
import com.www.applyword.adapter.JobPositionTimeAdapter;
import com.www.applyword.adapter.JobPositionTimeAdapter2;
import com.www.applyword.base.BaseActivity;
import com.www.applyword.bean.LoginBean;
import com.www.applyword.bean.ResultBean;
import com.www.applyword.bean.ResumeBean;
import com.www.applyword.event.EventConstants;
import com.www.applyword.event.MessageEvent;
import com.www.applyword.http.CallBack;
import com.www.applyword.http.HttpClient;
import com.www.applyword.utils.SPUtil;
import com.www.applyword.utils.Utils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.www.applyword.utils.Utils.getDeviceDensity;

/**
 * author : huang
 * date   : 2019/10/25 0025 9:51
 * version: 1.0
 */
public class JobExpectActivity extends BaseActivity {
    @BindView(R.id.tv_job_word)
    TextView tvJobWord;
    @BindView(R.id.tv_job)
    TextView tvJob;
    @BindView(R.id.tv_entrance_end_time)
    TextView tvEntranceEndTime;
    @BindView(R.id.tv_time2)
    TextView tv_time;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_salaryExpectation)
    TextView tv_salaryExpectation;
    @BindView(R.id.ll_start_time)
    LinearLayout llStartTime;
    @BindView(R.id.ll_end_time)
    LinearLayout llEndTime;
    @BindView(R.id.ll_address)
    LinearLayout ll_address;
    private String typeName;

    private Dialog dialog;

    private  List<ResultBean> jobList = new ArrayList<>();

    private PopupWindow mValidatePayPasswordPopWindow;


    OptionsPickerView pvOptions;
    //自行添加一些string
    private List<String> gradeData = new ArrayList<>();
    private JobPositionTimeAdapter mHotJobAdapter;
    private JobPositionTimeAdapter2 mHotJobAdapter2;
    private String position_id;

    private String date[] = {"9:00", "9:30","10:00","10:30","11:00","11:30","12:00","12:30","13:00","13:30","14:00","14:30"
                              ,"15:00", "15:30","16:00","16:30","17:00","17:30","18:00","18:30","19:00","19:30","20:00","20:30"
                              ,"21:00", "21:30","22:00","22:30","23:00","23:30","24:00","00:30","01:00","01:30","02:00","02:30"
                               ,"03:00", "03:30","04:00","04:30","05:00","05:30","06:00","06:30","07:00","07:30","08:00","08:30"};

    private String date2[] = {"100", "200","300","400","500","600","700","800","900","1000","1500","2000"
                              ,"2500", "3000","3500","4000","4500","5000","5500","6000","6500","7000","7500","8000"
                              ,"8500", "9000","9500","10000"};
    private String time;
    private String time2;
    private String money;
    private String money2;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.job_expect_activity);
        setTitle("工作期望");
        setRringTitle("保存");
        tv_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveResumeJob();
            }
        });
    }

    private void saveResumeJob() {
         /*  if (TextUtils.isEmpty(etSchool.getText().toString().trim())) {
            Utils.showToastSafe("请填写公司名称");
            return;
        }*/
       /* if (TextUtils.isEmpty(tvEntranceStartTime.getText().toString().trim())) {
            Utils.showToastSafe("请选择开始时间");
            return;
        }*/
        if (TextUtils.isEmpty(tvJobWord.getText().toString().trim())) {
            Utils.showToastSafe("请选择工作性质");
            return;
        }
      /*  if (TextUtils.isEmpty(tvJobType.getText().toString().trim())) {
            Utils.showToastSafe("请选择工作类型");
            return;
        }*/

        Map<String, Object> params = new HashMap<>();
        params.put("ResumeBasic_UserID", SPUtil.getString(Constants.USERID));
        params.put("ResumeBasic_WorkNature",tvJobWord.getText().toString().trim()); //工作性质
        params.put("ResumeBasic_PositionID",position_id);  //
        params.put("ResumeBasic_FreeTime",tv_time.getText().toString().trim());
        params.put("ResumeBasic_WorkTime",tvEntranceEndTime.getText().toString());
        params.put("ResumeBasic_PositionName",tvJob.getText().toString()); //期望职位
        params.put("ResumeBasic_Region",tvAddress.getText().toString()); //偏好区域
        params.put("ResumeBasic_SalaryExpectation",tv_salaryExpectation.getText().toString().trim()); //薪资
        HttpClient.post(JobExpectActivity.this, Constants.RESUMEJOBEXPECTATIONS, params,new CallBack<LoginBean>() {
            @Override
            public void onSuccess(LoginBean result) {
                MessageEvent messageEvent = new MessageEvent();
                messageEvent.setMessageKey(EventConstants.DEL_RESUMESCHOOL);
                EventBus.getDefault().post(messageEvent);
                Utils.showToastSafe("保存成功");
                finish();
            }
        });
    }

    @Override
    protected void loadData() {
        ResumeBean.ResumeBasicBean  resumeBasic = (ResumeBean.ResumeBasicBean) getIntent().getSerializableExtra("resumeBasic");
        if (null != resumeBasic){
            position_id =  resumeBasic.getResumeBasic_PositionID();
            if (!TextUtils.isEmpty(resumeBasic.getResumeBasic_WorkNature()) && resumeBasic.getResumeBasic_WorkNature().contains("短期兼职")){
                llStartTime.setVisibility(View.VISIBLE);
                llEndTime.setVisibility(View.VISIBLE);
            }else if (resumeBasic.getResumeBasic_WorkNature().contains("找什么工作")){
                llStartTime.setVisibility(View.VISIBLE);
                llEndTime.setVisibility(View.VISIBLE);
            }else if (resumeBasic.getResumeBasic_WorkNature().contains("在家赚钱")){
                llStartTime.setVisibility(View.GONE);
                llEndTime.setVisibility(View.GONE);
                ll_address.setVisibility(View.GONE);
            }else {
                llStartTime.setVisibility(View.GONE);
                llEndTime.setVisibility(View.GONE);
                ll_address.setVisibility(View.VISIBLE);
            }

            if (!TextUtils.isEmpty(resumeBasic.getResumeBasic_WorkNature())){
                tvJobWord.setText(resumeBasic.getResumeBasic_WorkNature()); //我想找长期稳定工作
            }
            if (!TextUtils.isEmpty(resumeBasic.getResumeBasic_Region())){  //工作区城
                tvAddress.setText(resumeBasic.getResumeBasic_Region());
            }
            if (!TextUtils.isEmpty(resumeBasic.getResumeBasic_PositionName())){
                tvJob.setText(resumeBasic.getResumeBasic_PositionName());
            }
            if (!TextUtils.isEmpty(resumeBasic.getResumeBasic_WorkTime())){
                tvEntranceEndTime.setText(resumeBasic.getResumeBasic_WorkTime());
            }
            if (!TextUtils.isEmpty(resumeBasic.getResumeBasic_WorkTime())){
                tv_time.setText(resumeBasic.getResumeBasic_FreeTime());
            }
            if (!TextUtils.isEmpty(resumeBasic.getResumeBasic_SalaryExpectation())){
                tv_salaryExpectation.setText(resumeBasic.getResumeBasic_SalaryExpectation());
            }
        }
    }


    @OnClick({R.id.tv_job_word, R.id.tv_entrance_end_time, R.id.tv_address,R.id.tv_time2,R.id.tv_job,R.id.tv_salaryExpectation})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_job_word:
                typeName = "工作类型";
                showJobType(1);
                break;
            //工作时间
            case R.id.tv_entrance_end_time:
                showStartTime();
                break;
            case R.id.tv_address:
                showAddress();
                break;
                //空闲时间
            case R.id.tv_time2:
                typeName = "空闲时间";
                showJobType(2);
                break;
                //期望职位
            case R.id.tv_job:
                showJobPosition();
                break;
                //期望月薪
            case R.id.tv_salaryExpectation:
                showMoneyPosition();
                break;
            default:
        }
    }


    private void showJobPosition() {
        hideInput2();
        Intent intent = new Intent(JobExpectActivity.this, JobPostionActivity.class);
     //   startActivity(intent);
        startActivityForResult(intent, 10);
        JobExpectActivity.this.overridePendingTransition(R.anim.push_top_in,
                R.anim.push_top_out);
    }

    private void showAddress() {
        hideInput2();
        //申明对象
        CityPickerView mPicker=new CityPickerView();
        //预先加载仿iOS滚轮实现的全部数据（oncreate()中）
        mPicker.init(this);
        //配置
        CityConfig cityConfig = new CityConfig.Builder()
                .title("选择城市")//标题
                .titleTextSize(10)//标题文字大小
                .titleTextColor("#585858")//标题文字颜  色
                .titleBackgroundColor("#ffdddddd")//标题栏背景色
                .confirTextColor("#ffe1163c")//确认按钮文字颜色
                .confirmText("确定")//确认按钮文字
                .confirmTextSize(10)//确认按钮文字大小
                .cancelTextColor("#585858")//取消按钮文字颜色
                .cancelText("取消")//取消按钮文字
                .cancelTextSize(10)//取消按钮文字大小
                .setCityWheelType(CityConfig.WheelType.PRO_CITY_DIS)//显示类，只显示省份一级，显示省市两级还是显示省市区三级
                .showBackground(true)//是否显示半透明背景
                .visibleItemsCount(7)//显示item的数量
                .province("湖北省")//默认显示的省份
                .city("武汉市")//默认显示省份下面的城市
                .district("洪山区")//默认显示省市下面的区县数据
                .provinceCyclic(true)//省份滚轮是否可以循环滚动
                .cityCyclic(true)//城市滚轮是否可以循环滚动
                .districtCyclic(true)//区县滚轮是否循环滚动
                .setCustomItemLayout(R.layout.item_city)//自定义item的布局
                .setCustomItemTextViewId(R.id.item_city_name_tv)//自定义item布局里面的textViewid
                .drawShadows(false)//滚轮不显示模糊效果
                .setLineHeigh(1)//中间横线的高度
                .setLineColor("#fff9c21a")
                .setShowGAT(true)//是否显示港澳台数据，默认不显示
                .build();
        //添加配置
        mPicker.setConfig(cityConfig);
        //显示
        mPicker.showCityPicker();
        //监听选择点击事件及返回结果
        mPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                super.onSelected(province, city, district);
                //为TextView赋值
                tvAddress.setText(province + "-" + city + "-" + district);
            }

            @Override
            public void onCancel() {
                super.onCancel();
            }
        });
    }

    private void showJobType(int type) {
        hideInput2();
        if (type == 1) {
            gradeData.clear();
            gradeData.add("我想找长期稳定工作");
            gradeData.add("我想找短期兼职工作");
            gradeData.add("在家赚钱");
            gradeData.add("我找什么工作都行");
        } else if (type == 2) {
            gradeData.clear();
            gradeData.add("不限");
            gradeData.add("仅周末");
            gradeData.add("仅工作日");
            gradeData.add("寒暑假");
            gradeData.add("节假日");
        } else if (type == 3) {
            gradeData.clear();
            gradeData.add("在读");
            gradeData.add("已毕业");
        } else if (type == 4) {
            gradeData.clear();
            gradeData.add("不限");
            gradeData.add("18-30岁");
            gradeData.add("30-40岁");
            gradeData.add("50岁以下");
        }
        pvOptions = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            if (type == 1) {
                tvJobWord.setText(gradeData.get(options1));
                if (gradeData.get(options1).equals("我想找短期兼职工作") || gradeData.get(options1).equals("我找什么工作都行") ){
                    llStartTime.setVisibility(View.VISIBLE);
                    llEndTime.setVisibility(View.VISIBLE);
                }else if (gradeData.get(options1).equals("在家赚钱")){
                    llStartTime.setVisibility(View.GONE);
                    llEndTime.setVisibility(View.GONE);
                    ll_address.setVisibility(View.GONE);
                }else {
                    llStartTime.setVisibility(View.GONE);
                    llEndTime.setVisibility(View.GONE);
                    ll_address.setVisibility(View.VISIBLE);
                }
            }else {
                tv_time.setText(gradeData.get(options1));
            }
        })
                .setTitleText(typeName)
                .setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setSubCalSize(10)//确定和取消文字大小
                .setSubmitColor(0xffFF6767)//确定按钮文字颜色
                .setCancelColor(0xff999999)//取消按钮文字颜色
                .setTitleBgColor(0xffF4F4F4)//标题背景颜色 Night mode
                .setTitleSize(10)
                .setContentTextSize(12)//滚轮文字大小
                .setTextColorCenter(0xff333333)
                .setTextColorOut(0x999999)
                .setDividerColor(0xffEEEEEE)
                .setCyclic(false, false, false)//循环与否
                .setSelectOptions(0, 0, 0)  //设置默认选中项
                .setOutSideCancelable(true)//点击外部dismiss default true
                .isDialog(false)//是否显示为对话框样式
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .setLineSpacingMultiplier((float) 2.5) //设置item的高度
                .build();
        pvOptions.setPicker(gradeData);
        pvOptions.show();
    }

    private void hideInput2() {
       /* InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }*/
    }

    public TextView tv_prv_select;
    public TextView tv_prv_select2;
    //工作时间
    private void showStartTime() {
        hideInput2();
        setBackgroundAlpha((float) 0.4);
        View contentView = LayoutInflater.from(this).inflate(R.layout.popwindow_job_time, null);
        final TextView tv_cancel = contentView.findViewById(R.id.tv_cancel);
        final TextView tv_ok = contentView.findViewById(R.id.tv_ok);
        final RecyclerView rv_left = contentView.findViewById(R.id.rv_left);
        final RecyclerView rv_right = contentView.findViewById(R.id.rv_right);

        rv_left.setLayoutManager(new LinearLayoutManager(JobExpectActivity.this));
        rv_left.setItemAnimator(new DefaultItemAnimator());
        mHotJobAdapter = new JobPositionTimeAdapter(JobExpectActivity.this);
        rv_left.setAdapter(mHotJobAdapter);
        mHotJobAdapter.addAll(Arrays.asList(date));

        rv_right.setLayoutManager(new LinearLayoutManager(JobExpectActivity.this));
        rv_right.setItemAnimator(new DefaultItemAnimator());
        mHotJobAdapter2 = new JobPositionTimeAdapter2(JobExpectActivity.this);
        rv_right.setAdapter(mHotJobAdapter2);
        mHotJobAdapter2.addAll(Arrays.asList(date));

        mHotJobAdapter.setOnItemClickListener(new CommonRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int i) {
                TextView tv_check =  view.findViewById(R.id.tv_job);
                if (tv_prv_select == tv_check) {
                    tv_check.setSelected(false);
                    tv_prv_select = null;
                    return;
                }

                tv_check.setSelected(true);
                if (tv_prv_select != null) {
                    tv_prv_select.setSelected(false);
                }
                tv_prv_select = tv_check;
                time = date[i];
            }
        });

        mHotJobAdapter2.setOnItemClickListener(new CommonRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int i) {
                TextView tv_check =  view.findViewById(R.id.tv_job);
                if (tv_prv_select2 == tv_check) {
                    tv_check.setSelected(false);
                    tv_prv_select2 = null;
                    return;
                }

                tv_check.setSelected(true);
                if (tv_prv_select2 != null) {
                    tv_prv_select2.setSelected(false);
                }
                tv_prv_select2 = tv_check;
                time2 = date[i];
            }
        });

        tv_cancel.setOnClickListener(v -> mValidatePayPasswordPopWindow.dismiss());
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(time)){
                    Utils.showToastSafe("请选择开始时间");
                    return;
                }
                if (TextUtils.isEmpty(time2)){
                    Utils.showToastSafe("请选择结束时间");
                    return;
                }
                if (time.equals(time2)){
                    Utils.showToastSafe("开始时间等于结束时间");
                    return;
                }
                tvEntranceEndTime.setText(time + "—" + time2);
                mValidatePayPasswordPopWindow.dismiss();
            }
        });

        mValidatePayPasswordPopWindow = new PopupWindow(contentView,
                (int) (getDeviceDensity().widthPixels), LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mValidatePayPasswordPopWindow.setContentView(contentView);
        View rootView = LayoutInflater.from(JobExpectActivity.this).inflate(R.layout.hot_job_activity, null);
        mValidatePayPasswordPopWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
        mValidatePayPasswordPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1);
            }
        });
    }


    //期望月薪
    private void showMoneyPosition() {
        hideInput2();
        setBackgroundAlpha((float) 0.4);
        View contentView = LayoutInflater.from(this).inflate(R.layout.popwindow_job_time, null);
        final TextView tv_cancel = contentView.findViewById(R.id.tv_cancel);
        final TextView tv_ok = contentView.findViewById(R.id.tv_ok);
        final RecyclerView rv_left = contentView.findViewById(R.id.rv_left);
        final RecyclerView rv_right = contentView.findViewById(R.id.rv_right);

        rv_left.setLayoutManager(new LinearLayoutManager(JobExpectActivity.this));
        rv_left.setItemAnimator(new DefaultItemAnimator());
        mHotJobAdapter = new JobPositionTimeAdapter(JobExpectActivity.this);
        rv_left.setAdapter(mHotJobAdapter);
        mHotJobAdapter.addAll(Arrays.asList(date2));

        rv_right.setLayoutManager(new LinearLayoutManager(JobExpectActivity.this));
        rv_right.setItemAnimator(new DefaultItemAnimator());
        mHotJobAdapter2 = new JobPositionTimeAdapter2(JobExpectActivity.this);
        rv_right.setAdapter(mHotJobAdapter2);
        mHotJobAdapter2.addAll(Arrays.asList(date2));

        mHotJobAdapter.setOnItemClickListener(new CommonRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int i) {
                TextView tv_check =  view.findViewById(R.id.tv_job);
                if (tv_prv_select == tv_check) {
                    tv_check.setSelected(false);
                    tv_prv_select = null;
                    return;
                }

                tv_check.setSelected(true);
                if (tv_prv_select != null) {
                    tv_prv_select.setSelected(false);
                }
                tv_prv_select = tv_check;
                money = date2[i];
            }
        });

        mHotJobAdapter2.setOnItemClickListener(new CommonRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int i) {
                TextView tv_check =  view.findViewById(R.id.tv_job);
                if (tv_prv_select2 == tv_check) {
                    tv_check.setSelected(false);
                    tv_prv_select2 = null;
                    return;
                }

                tv_check.setSelected(true);
                if (tv_prv_select2 != null) {
                    tv_prv_select2.setSelected(false);
                }
                tv_prv_select2 = tv_check;
                money2 = date2[i];
            }
        });

        tv_cancel.setOnClickListener(v -> mValidatePayPasswordPopWindow.dismiss());
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(money)){
                    Utils.showToastSafe("请选择最底期望月薪");
                    return;
                }
                if (TextUtils.isEmpty(money2)){
                    Utils.showToastSafe("请选择最高期望月薪");
                    return;
                }
                if (Integer.parseInt(money) >= Integer.parseInt(money2)){
                    Utils.showToastSafe("最底期望月薪要小于最高期望月薪");
                    return;
                }
                //
                tv_salaryExpectation.setText(money + "—" + money2);
                mValidatePayPasswordPopWindow.dismiss();
            }
        });

        mValidatePayPasswordPopWindow = new PopupWindow(contentView,
                (int) (getDeviceDensity().widthPixels), LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mValidatePayPasswordPopWindow.setContentView(contentView);
        View rootView = LayoutInflater.from(JobExpectActivity.this).inflate(R.layout.hot_job_activity, null);
        mValidatePayPasswordPopWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
        mValidatePayPasswordPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1);
            }
        });
    }


    private void setBackgroundAlpha(float v) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = v;
        getWindow().setAttributes(lp);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10 && resultCode == 20) {
            position_id = data.getStringExtra("position_id");
            String position_name = data.getStringExtra("position_name");
            tvJob.setText(position_name);
        }
    }
}
